package gobase

import (
	"fmt"
	"regexp"
	"strings"
)

/*
*
忽略大小写
*/
func ReplaceAll(s string, old, new string) string {
	strRegFind := fmt.Sprintf("(?i)%s", regexp.QuoteMeta(old))

	reg, err := regexp.Compile(strRegFind)
	if err != nil {
		return s
	}

	return string(reg.ReplaceAll([]byte(s), []byte(new)))
}

func ReplaceReg(s string, regP string, new string) (string, error) {
	reg, err := regexp.Compile(regP)
	if err != nil {
		return "", err
	}

	return string(reg.ReplaceAll([]byte(s), []byte(new))), nil
}

/*
`<td>a</td><td>b</td>`
GetBetween(str, "<td>", "</td>") = a

GetBetween("$now$", "$", "$") = "now"
*/
func GetBetween(str string, start, end string, idx int) string {

	j := 0
	for {
		n := strings.Index(str, start)
		if n == -1 {
			return ""
		}
		str = string([]byte(str)[n+len(start):])
		m := strings.Index(str, end)
		if m == -1 {
			return ""
		}
		if j == idx {
			str = string([]byte(str)[:m])
			return str
		} else {
			str = string([]byte(str)[m+len(end):])
			if len(str) <= len(start) {
				return ""
			}
		}
		j++
	}
}

// 注意 getKeyValue返回的值如果继续包含replkey, 可能会造成死循环
func ReplacePlaceholder(s string, start, end string, getKeyValue func(key string) (v string, ok bool)) string {
	idx := 0
	for {
		id := GetBetween(s, start, end, idx)
		if len(id) == 0 {
			break
		}

		if v, ok := getKeyValue(id); ok {
			replkey := fmt.Sprintf("%s%s%s", start, id, end)
			if replkey == v { // 直接跳过，否则会造成死循环
				idx++
			} else {
				if strings.Contains(v, replkey) { // 包含了， replkey， 将会再次替换造成死循环
					idx++
				} else {
					// 注意 返回的值(v)如果继续包含replkey, 会造成死循环
					s = strings.ReplaceAll(s, replkey, v)
				}

			}
		} else {
			idx++
		}
	}
	return s
}
